import { OneModal } from '@/components/one-ui';
import React, { Ref, useRef } from 'react';
import { AddAttachForm } from './AddAttachForm';
import { IOneModalRef } from '@/pages/type';
import { onCloseModalCommon, getKeyRouter } from '@/utils';
import { Button, Form, Spin, message } from 'antd';

interface UpdateNeedAttachAddModalAPI {
  prefixCls: string;
  onClose: () => void;
  addContractAttachRun: any;
  contractDetailInfo: Record<string, any>;
  reloadDetail: any;
  setFiledDataSource: any;
  onOpenReadOfdWord: any;
}

/**
 * 添加附件弹窗
 * */
export const OpenAttachModal: React.FC<UpdateNeedAttachAddModalAPI> = ({
  prefixCls,
  onClose,
  addContractAttachRun,
  contractDetailInfo,
  reloadDetail,
  setFiledDataSource,
  onOpenReadOfdWord,
}) => {
  const addAttachRef: Ref<IOneModalRef> = useRef(null);

  /**添加附件的ref*/
  const [attachForm] = Form.useForm();

  /** 保存方法 */
  const save = () => {
    attachForm?.validateFields()?.then(async (values: any) => {
      let param = {
        contractID: contractDetailInfo?.id,
        versionNum: contractDetailInfo?.versionNum,
        key: `filedTable-${getKeyRouter()}`,
        modifyFlag: 0,
        ...values,
      };
      delete param['attachURLDel'];
      let result = await addContractAttachRun(param);
      if (result && result?.msgFlag) {
        message.success('添加成功');
        let res = await reloadDetail({
          id: result?.obj?.contractID,
        });
        if (res && res?.msgFlag) {
          setFiledDataSource(res?.obj?.attachList);
        }
        onCloseModalCommon(addAttachRef);
      }
    });
  };

  return (
    <OneModal
      open={true}
      getContainer={false}
      ref={addAttachRef}
      title={'添加附件'}
      width={700}
      bodyStyle={{ padding: '15px' }}
      onCancel={onClose}
      footer={[
        <Button
          key="back"
          onClick={() => {
            onCloseModalCommon(addAttachRef);
          }}
        >
          取消
        </Button>,
        <Button
          key="submit"
          type="primary"
          onClick={() => {
            save();
          }}
        >
          确定
        </Button>,
      ]}
    >
      <Spin spinning={false}>
        <AddAttachForm formRef={attachForm} prefixCls={prefixCls} onOpenReadOfdWord={onOpenReadOfdWord} />
      </Spin>
    </OneModal>
  );
};
